/**
 * @desc: 批量新增组合商品弹框
 * @author: fj
 */

import React, { useState, useEffect, useRef } from "react";
import CommonModal from "@/components/CommonModal";
import CommonImgsLoad from "@/components/CommonImgsLoad";
import CommonTable from "@/components/CommonTable";
import CommonLoading from "@/components/CommonLoading";
import CommonZjfImg from "@/components/CommonImg/ZifComponent";
import CommonSysImg from "@/components/CommonImg/SysComponent";
import AddGoodsModal from "./AddGoodsModal";
import EditGoodsModal from "./EditGoodsModal";
import GoodsDetail from "./GoodsDetail";
import CombinPreview from "./CombinPreview";
import { cloneDeep, findIndex, groupBy } from "lodash";
import { doExchange } from "@/utils/utils.jsx";
import { getZjfGoodsBatchByIdsZh, getSysGoodsBatchByIdsZh } from "../service";
import { Button, Input, Form, Alert, InputNumber, Popconfirm, Switch, message } from "antd";
import styles from "./GoodsList.module.less";

const BatchAddCombine = ({ visible, handleCancel, handleOk }) => {
	const [addVisible, setAddVisible] = useState(false); //添加商品弹窗的visible
	const [editVisible, setEditVisible] = useState(false); //编辑颜色规格弹窗的visible
	const [addGoodsList, setAddGoodsList] = useState([]); //添加的商品数据
	const [detailVisible, setDetailVisible] = useState(false); //详情弹窗的visibel
	const [detailiData, setDetailData] = useState([]); //商品详情的数据
	const [previewVisible, setPreviewVisible] = useState(false); //组合预览的visible
	const [perviewArr, setPerviewArr] = useState([]); //组合预览的颜色规格列表
	const [recordData, setRecordData] = useState({}); //单行的数据
	const [index, setIndex] = useState(0); // 编辑颜色规格选中的index
	const [scrollKey, setScrollKey] = useState(1);
	const scrollEnd = useRef(null);
	const [type, setType] = useState(1);
	const [loading, setLoading] = useState(false);
	const [form] = Form.useForm();

	const [isOpen, setOpen] = useState(false);

	useEffect(() => {
		if (addGoodsList) {
			addGoodsList?.length && setAddGoodsList([]);
		}
	}, [isOpen]);

	useEffect(() => {
		addGoodsList?.length && console.log("addGoodsList", addGoodsList);
	}, [addGoodsList]);

	const columns = [
		{
			title: "序号",
			dataIndex: "index",
			key: "index",
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: "供应商名称",
			dataIndex: "storeName",
			key: "storeName",
			width: 80,
			render: (_, record) => {
				if (record.customType == "sys") {
					return <span className="table-weight-text">系统商品</span>;
				} else {
					return <span className="table-weight-text">{record.storeName}</span>;
				}
			}
		},
		{
			title: "商品",
			width: 150,
			dataIndex: "goodsName",
			key: "goodsName",
			render: (_, record) => {
				return (
					<div style={{ display: "flex", alignItems: "center" }}>
						{record.customType == "sys" ? (
							<CommonSysImg img={record.goodsImage} storeId={record.storeId} style={{ marginRight: "8px" }} />
						) : (
							<CommonZjfImg img={record.goodsImage} storeId={record.storeId} style={{ marginRight: "8px" }} />
						)}

						<div style={{ display: "flex", flexDirection: "column", flex: 1 }}>
							<>
								<span>
									{record.goodsName}
									{record.goodsSpec}
								</span>
							</>
						</div>
					</div>
				);
			}
		},
		{
			title: "规格",
			width: 80,
			dataIndex: "sizeNum",
			key: "sizeNum",
			render: (_, record) => {
				return (
					<div>
						<div>{record.sizeNum}个尺码</div>
						<div>{record.colorNum}个颜色</div>
						{record.customType == "sys" && record.otherNum > 0 ? <div>{record.otherNum}个其他属性</div> : ""}
					</div>
				);
			}
		},
		{
			title: "颜色规格数",
			width: 80,
			dataIndex: "goodsNum",
			key: "goodsNum",
			render: (_, record) => {
				return (
					<a onClick={() => getGoodsDetail(record)} className="common-color1">
						{record.goodsNum}
					</a>
				);
			}
		},
		{
			title: "数量(个)",
			width: 100,
			dataIndex: "goodsCount",
			key: "goodsCount",
			render: (text, record, index) => (
				<div>
					<InputNumber min={1} value={text} precision={0} onBlur={e => handleNumChange(e, record, index)} />
				</div>
			)
		},
		{
			title: "操作",
			width: 100,
			key: "opera",
			render: (text, record, index) => (
				<span className="opera-span-common">
					<span onClick={() => editGoods(record, index)}>编辑</span>
					<i>|</i>
					<Popconfirm title="确定删除?" onConfirm={() => handleDeleteGoods(index)} okText="确定" cancelText="取消">
						<span>删除</span>
					</Popconfirm>
				</span>
			)
		}
	];

	//滚动到底部
	const handleScroll = () => {
		if (scrollEnd.current && scrollKey > 1) {
			const scrollHeight = scrollEnd.current.scrollHeight; //里面div的实际高度
			const height = scrollEnd.current.clientHeight; //网页可见高度
			const maxScrollTop = scrollHeight - height;
			scrollEnd.current.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
			//如果实际高度大于可见高度，说明是有滚动条的，则直接把网页被卷去的高度设置为两个div的高度差，实际效果就是滚动到底部了。
		}
	};

	useEffect(() => {
		handleScroll();
	}, [scrollKey]);

	//修改商品数量
	const handleNumChange = (e, record, index) => {
		const reg = /^[1-9]\d*$/;
		const val = e.target.value;
		if (reg.test(val)) {
			const arr = cloneDeep(addGoodsList);
			const obj = cloneDeep(record);
			obj.goodsCount = val;
			arr.splice(index, 1, obj);
			setAddGoodsList(arr);
		} else {
			message.info("请输入正整数");
		}
	};

	//当前可组合数
	const showCombinCount = () => {
		const arr = cloneDeep(addGoodsList);
		if (isOpen) {
			return arr.reduce((prev, cur) => {
				return prev + cur.sizeNum;
			}, 0);
		}
		return arr.reduce((prev, cur) => {
			return prev * cur.goodsNum;
		}, 1);
	};

	//获取商品的明细
	const getGoodsDetail = async record => {
		if (record.customType == "shop") {
			//供应商商品
			setType(1);
			const goodsIds = [];
			record.storeGoodsArr.map(item => {
				goodsIds.push(item.goodsId);
			});
			const { success, data = [] } = await getZjfGoodsBatchByIdsZh(goodsIds);
			if (success) {
				setDetailData(data);
			}
		} else {
			//系统商品
			setType(2);
			const sysGoodsIds = [];
			record.sysGoodsArr.map(item => {
				sysGoodsIds.push(item.id);
			});
			const { success, data = [] } = await getSysGoodsBatchByIdsZh(sysGoodsIds);
			if (success) {
				setDetailData(data);
			}
		}
		setDetailVisible(true);
	};

	//删除商品
	const handleDeleteGoods = index => {
		const arr = cloneDeep(addGoodsList);
		arr.splice(index, 1);
		message.success("删除成功");
		setAddGoodsList(arr);
	};

	//编辑商品
	const editGoods = (record, index) => {
		if (record.customType == "shop") {
			setType(1);
		} else {
			setType(2);
		}
		setRecordData(record);
		setIndex(index);
		setEditVisible(true);
	};

	//点击添加商品
	const handleAddGoods = () => {
		setAddVisible(true);
	};

	//图片上传回调手动更新表单值
	const handleDone = val => {
		form.setFieldsValue({
			composeImage: val
		});
	};

	//单个获取商品详情规格
	const getDetail = item => {
		return new Promise(async (resolve, reject) => {
			if (item.customType == "shop") {
				//供应商商品
				const goodsIds = [];
				const newDataList = [];
				item.storeGoodsArr.map(items => {
					goodsIds.push(items.goodsId);
				});
				const { success, data = [] } = await getZjfGoodsBatchByIdsZh(goodsIds);
				if (success) {
					data.map(z => {
						newDataList.push({
							...z,
							goodsCount: item.goodsCount
						});
					});
					resolve(newDataList);
				} else {
					reject("网络错误");
				}
			} else {
				//系统商品
				const sysGoodsIds = [];
				const newDataList = [];
				item.sysGoodsArr.map(items => {
					sysGoodsIds.push(items.id);
				});
				const { success, data = [] } = await getSysGoodsBatchByIdsZh(sysGoodsIds);
				if (success) {
					data.map(z => {
						newDataList.push({
							...z,
							goodsCount: item.goodsCount
						});
					});
					resolve(newDataList);
				} else {
					reject("网络错误");
				}
			}
		});
	};

	//获取所有颜色规格的明细数据
	const getAllDetail = () => {
		if (isOpen) {
			const arr = [];
			addGoodsList.map(item => {
				if (item.customType == "shop") {
					const obj = groupBy(item.storeGoodsArr, "size"),
						list = Object.keys(obj);
					list.map(child => {
						arr.push({
							...item,
							storeGoodsArr: obj[child]
						});
					});
				} else {
					const obj = groupBy(item.sysGoodsArr, "sizeAtt"),
						list = Object.keys(obj);
					list.map(child => {
						arr.push({
							...item,
							sysGoodsArr: obj[child]
						});
					});
				}
			});
			let promiseArr = arr.map(item => {
				return getDetail(item);
			});
			return Promise.all(promiseArr).then(value => {
				return value;
			});
		} else {
			const arr = cloneDeep(addGoodsList);
			let promiseArr = arr.map(item => {
				return getDetail(item);
			});
			return Promise.all(promiseArr).then(value => {
				return doExchange(value);
			});
		}
	};

	//取消事件。重置数据
	const onCancel = () => {
		form.resetFields();
		handleCancel();
	};

	//子商品的展示（如果是库存商品，则显示上面弹框的网店商品或系统商品，如果是拿货商品或供应商直发商品，
	//则显示匹配的供应商商品，样式如左图，商品类型读取上面弹框的商品类型）
	const handleGooodsItem = items => {
		if (items.hasOwnProperty("platformGoods")) {
			//供应商维度
			let obj = {};
			if (items.platformGoods.id) {
				//代表已匹配
				if (items.platformGoods.deliverType == 3) {
					//已匹配的库存商品展示网店商品
					obj = {
						...items.platformGoods,
						goodsNum: items.goodsCount,
						goodsPrice: items.platformGoods.ecGoodsPrice, //平台商品价格字段需要修改用于预览时计算
						type: 2,
						productId: items.platformGoods.id,
						productType: 2,
						customType: "shop",
						storeId: items.matchingGoods.storeId,
						goodsId: items.matchingGoods.goodsId,
						goodsCommonId: items.matchingGoods.goodsCommonId
					};
				} else {
					obj = {
						...items.matchingGoods,
						goodsNum: items.goodsCount,
						type: 2,
						productId: items.platformGoods.id,
						productType: 2,
						customType: "zjf",
						deliverType: items.platformGoods.deliverType
					};
				}
			} else {
				obj = {
					...items.matchingGoods,
					goodsNum: items.goodsCount,
					type: 2,
					productId: 0,
					productType: 2,
					customType: "zjf"
				};
			}
			return obj;
		} else {
			//系统维度
			let obj = {};
			if (items.matchingGoods.goodsId) {
				//代表已匹配
				if (items.sysformGoods.deliverType != 3) {
					//非库存
					obj = {
						...items.matchingGoods,
						goodsNum: items.goodsCount,
						type: 2,
						productId: items.sysformGoods.id,
						productType: 1,
						customType: "zjf",
						deliverType: items.sysformGoods.deliverType
					};
				} else {
					obj = {
						...items.sysformGoods,
						goodsId: items.matchingGoods.goodsId,
						goodsCommonId: items.matchingGoods.goodsCommonId,
						storeId: items.matchingGoods.storeId,
						goodsNum: items.goodsCount,
						type: 2,
						productId: items.sysformGoods.id,
						productType: 1,
						customType: "sys"
					};
				}
			} else {
				obj = {
					...items.sysformGoods,
					goodsNum: items.goodsCount,
					type: 1,
					productId: items.sysformGoods.id,
					productType: 1,
					customType: "sys"
				};
			}
			return obj;
		}
	};

	//保存进入下一步
	const onSave = () => {
		const arr = []; //最后预览的数组
		form
			.validateFields()
			.then(async value => {
				if (addGoodsList.length) {
					const combinArr = await getAllDetail(); // 子商品的集合
					combinArr.map((item, index) => {
						let goodsArr = []; //
						if (item.length > 0) {
							item.map(items => {
								goodsArr.push(handleGooodsItem(items));
							});
						} else {
							goodsArr.push(handleGooodsItem(item));
						}
						arr.push({
							...value,
							code: value.code ? value.code + (index + 1) : "",
							nameRepeat: false,
							codeRepeat: false,
							channelId: "",
							money: "",
							subGoodsArr: goodsArr
						});
					});
					setPerviewArr(arr);
					setPreviewVisible(true);
				} else {
					message.error("未选择商品");
				}
			})
			.catch(err => {
				console.log(err);
			});
	};

	//添加商品的porps
	const AddGoodsProps = {
		visible: addVisible,
		handleCancel() {
			setAddVisible(false);
		},
		handleOk(obj) {
			const arr = cloneDeep(addGoodsList);
			if (obj.customType == "shop") {
				//供应商商品
				if (findIndex(arr, ["goodsCommonid", obj.goodsCommonid]) > -1) {
					message.info("该商品已添加过，不能重复添加");
				} else {
					arr.push(obj);
					setAddGoodsList(arr);
					setAddVisible(false);
					setScrollKey(scrollKey + 1);
				}
			} else {
				//系统商品
				if (findIndex(arr, ["spuId", obj.spuId]) > -1) {
					message.info("该商品已添加过，不能重复添加");
				} else {
					arr.push(obj);
					setAddGoodsList(arr);
					setAddVisible(false);
					setScrollKey(scrollKey + 1);
				}
			}
		}
	};

	//编辑商品的porps
	const EditGoodsProps = {
		visible: editVisible,
		type: type,
		recordData,
		handleCancel() {
			setEditVisible(false);
		},
		handleOk(obj) {
			const arr = cloneDeep(addGoodsList);
			arr.splice(index, 1, obj);
			setAddGoodsList(arr);
			setEditVisible(false);
		}
	};

	//颜色规格详情的props
	const DetailProps = {
		visible: detailVisible,
		data: detailiData,
		type: type,
		handleCancel() {
			setDetailVisible(false);
		}
	};

	//组合预览的props
	const CombinPreviewProps = {
		visible: previewVisible,
		listArr: perviewArr,
		handleCancel() {
			setPreviewVisible(false);
		},
		handleOk() {
			setPreviewVisible(false);
			handleOk(); //关闭批量新增组合弹窗
		}
	};

	const CommonTableProps = {
		data: addGoodsList,
		columns,
		size: "small",
		rowkey: "goodsId"
	};

	return (
		<CommonModal
			title={"批量新增组合"}
			visible={visible}
			onCancel={onCancel}
			width="848px"
			overflowY="hidden"
			footer={[
				<Button key="back" onClick={onCancel}>
					取消
				</Button>,
				<Button key="save" type="primary" onClick={onSave}>
					下一步
				</Button>
			]}
		>
			<div ref={scrollEnd} style={{ maxHeight: "546px", overflow: "auto" }}>
				<Alert
					style={{ marginBottom: 16 }}
					message={
						<p>
							1、组合商品的第一商品，建议设置为第三方平台组合商品的主商品，方便检查核对！
							<br />
							2、注意：一个组合商品，是由商品1的所有规格商品+商品2的所有规格商品+商品3的所有规格商品...，不同商品之间相互组合形成组合，同时需要为每个组合设置发货渠道
						</p>
					}
					type="info"
				/>
				<Form
					//   onFinish={handleSubmit}
					form={form}
					name="batch-add-combina-goods"
					initialValues={{
						composeName: "",
						code: "",
						composeImage: ""
					}}
				>
					<Form.Item
						extra="如：通用床品5件套--岁月静好"
						name="composeName"
						label="组合名称"
						rules={[{ max: 60, message: "最多支持输入60个字符" }]}
					>
						<Input style={{ width: "px" }} placeholder="请输入组合商品名称" />
					</Form.Item>
					<Form.Item name="code" label="组合编号" rules={[{ max: 50, message: "最多支持输入50个字符" }]}>
						<Input style={{ width: "px" }} placeholder="请输入组合编号" />
					</Form.Item>
					<Form.Item extra="图片建议与第三方平台保存一致" name="composeImage" label="组合图片">
						<CommonImgsLoad handleOk={handleDone} />
					</Form.Item>
				</Form>
				<Button onClick={handleAddGoods} style={{ margin: "12px 0" }}>
					添加商品
				</Button>
				<span style={{ display: "inline-flex", alignItems: "center", marginLeft: "16px" }}>
					同一商品下同尺码组合：
					<Switch checked={isOpen} checkedChildren="开启" unCheckedChildren="禁用" onChange={e => setOpen(e)} />
				</span>
				<CommonTable {...CommonTableProps} style={{ marginBottom: "24px" }} />
				<div className={styles.combinCount}>当前可成组合数：{addGoodsList.length > 0 ? showCombinCount() : 0}</div>
				{addVisible && <AddGoodsModal {...AddGoodsProps} />}
				{editVisible && <EditGoodsModal {...EditGoodsProps} />}
				{detailVisible && <GoodsDetail {...DetailProps} />}
				{previewVisible && <CombinPreview {...CombinPreviewProps} />}
				<CommonLoading loading={loading} />
			</div>
		</CommonModal>
	);
};

export default React.memo(BatchAddCombine, (pre, next) => {
	if (pre.visible == next.visible) {
		return true;
	} else {
		return false;
	}
});
